package com.yingpai.fitness.dvp_2_0.main.activity.fitness;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.DateFormatUtil;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.HistroyDataBean;
import com.yingpai.fitness.entity.store.StoreDetailLeagueBean;
import com.yingpai.fitness.entity.store.StoreDetailPersonalBean;
import com.yingpai.fitness.dvp_2_0.main.widget.GlideImageLoader;
import com.yingpai.fitness.dvp_2_0.common.view.XGridView;
import com.yingpai.fitness.dvp_2_0.common.view.XListView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2018/8/14.
 */

public class StoreDetailActivity extends CommonActivity implements OnRefreshLoadMoreListener {
    @BindView(R.id.hot_child_banner)
    Banner hotChildBanner;
    @BindView(R.id.personal_calss)
    TextView personalCalss;
    @BindView(R.id.league_class)
    TextView leagueClass;
    @BindView(R.id.course1)
    TextView course1;
    @BindView(R.id.course2)
    TextView course2;
    @BindView(R.id.course3)
    TextView course3;
    @BindView(R.id.day)
    XGridView day;
    @BindView(R.id.listview)
    XListView listview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.classLl)
    LinearLayout classLl;
    private QuickAdapter<HistroyDataBean> dataQuickAdapter;
    private String flag = "personal";
    private int id;
    private List<String> bannerList = new ArrayList<>();
    private QuickAdapter<StoreDetailPersonalBean.MapData.DataData> personalAdapter;
    private String selectedDate;
    private int pageNum = 1;
    private int pageSize = 10;
    private QuickAdapter<StoreDetailLeagueBean.MapData.PageInfoData.ListData> leagueAdapter;
    private int course_flag;
    private Drawable drawable;
    private Drawable drawable1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.activity_store_detail);
    }


    private void dateRequest() {
        //日期
        String currentData = DateFormatUtil.getCurrentDate();
        String afterData = currentData;

        List<HistroyDataBean> data = new ArrayList<>();
        data.add(new HistroyDataBean(true, afterData.substring(5), getWeek(afterData)));

        for (int i = 1; i < 7; i++) {
            afterData = DateFormatUtil.getSpecifiedDayAfter(afterData);
            data.add(new HistroyDataBean(false, afterData.substring(5), getWeek(afterData)));
        }

        selectedDate = DateFormatUtil.getCurrentDate();

        dataQuickAdapter = new QuickAdapter<HistroyDataBean>(this, R.layout.item_day, data) {
            @Override
            protected void convert(final BaseAdapterHelper helper, final HistroyDataBean item) {
                TextView daytv = helper.getView(R.id.day);
                TextView weektv = helper.getView(R.id.week);
                View line = helper.getView(R.id.line);
                if (item.isCheck() == true) {
                    line.setVisibility(View.VISIBLE);
                    daytv.setTextColor(Color.parseColor("#d9b878"));
                    weektv.setTextColor(Color.parseColor("#d9b878"));
                } else {
                    line.setVisibility(View.INVISIBLE);
                    daytv.setTextColor(Color.parseColor("#333333"));
                    weektv.setTextColor(Color.parseColor("#333333"));
                }
                daytv.setText(item.getDay().replace("-", "."));
                weektv.setText(item.getMonth());

                LinearLayout itemDate = helper.getView(R.id.item_date);
                itemDate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (int i = 0; i < 7; i++) {
                            if (i == helper.getPosition()) {
                                selectedDate = selectedDate.substring(0, 5) + item.getDay();
                                dataQuickAdapter.getItem(helper.getPosition()).setCheck(true);
                            } else {
                                dataQuickAdapter.getItem(i).setCheck(false);
                            }
                        }
                        notifyDataSetChanged();

                        pageNum = 1;
                        requestLeagueData(course_flag);
                    }
                });
            }
        };
        day.setAdapter(dataQuickAdapter);
        day.setFocusable(false);
    }

    private void requestPersonalData() {
        showDialog(this,null);
        HttpParams params = new HttpParams();
        params.put("storeId", id);
        params.put("type", 1);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.GET_STORE_DETAIL_PERSONAL, params, Url.GET_STORE_DETAIL_PERSONAL, new Callback<StoreDetailPersonalBean>() {
            @Override
            public void onSuccess(StoreDetailPersonalBean storeDetailPersonalBean) {
                if (Constant.REQUEST_SUCCESS.equals(storeDetailPersonalBean.getResult())) {
                    bannerList.clear();
                    for (int i = 0; i < storeDetailPersonalBean.getMap().getPhotos().size(); i++) {
                        bannerList.add(storeDetailPersonalBean.getMap().getPhotos().get(i).getPhoto_url());
                    }
                    hotChildBanner.setImages(bannerList)
                            .setImageLoader(new GlideImageLoader())
                            .start();
                    personalAdapter.clear();
                    personalAdapter.addAll(storeDetailPersonalBean.getMap().getData());
                    personalAdapter.notifyDataSetChanged();
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                } else {
                    showToast(storeDetailPersonalBean.getMsg());
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    private void requestLeagueData(final int categoryId) {
        showDialog(this,null);
        HttpParams params = new HttpParams();
        params.put("categoryId", 7);
        params.put("dicCurriculumCategoryId", categoryId);
        params.put("storeId", id);
        params.put("date", selectedDate);
        params.put("pageNum", pageNum++);
        params.put("pageSize", pageSize);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.GET_STORE_DETAIL_LEAGUE, params, Url.GET_STORE_DETAIL_LEAGUE, new Callback<StoreDetailLeagueBean>() {
            @Override
            public void onSuccess(StoreDetailLeagueBean storeDetailLeagueBean) {
                if (Constant.REQUEST_SUCCESS.equals(storeDetailLeagueBean.getResult())) {
                    if (pageNum - 1 == 1) {
                        leagueAdapter.clear();
                        leagueAdapter.addAll(storeDetailLeagueBean.getMap().getPageInfo().getList());
                    } else {
                        leagueAdapter.addAll(storeDetailLeagueBean.getMap().getPageInfo().getList());
                    }
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    leagueAdapter.notifyDataSetChanged();

                    int pagecount;
                    if (storeDetailLeagueBean.getMap().getPageInfo().getTotal() % pageSize == 0) {
                        pagecount = storeDetailLeagueBean.getMap().getPageInfo().getTotal() / pageSize;
                    } else {
                        pagecount = storeDetailLeagueBean.getMap().getPageInfo().getTotal() / pageSize + 1;
                    }
                    if (pageNum > pagecount) {
                        refreshLayout.setNoMoreData(true);
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.setNoMoreData(false);
                    }
                } else {
                    showToast(storeDetailLeagueBean.getMsg());
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    private void courseRefresh() {
        course_flag = 5;
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());// 设置图片宽高
        course1.setCompoundDrawables(null, drawable, null, null);// 设置到控件中
        drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());// 设置图片宽高
        course2.setCompoundDrawables(null, drawable1, null, null);// 设置到控件中
        drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());// 设置图片宽高
        course3.setCompoundDrawables(null, drawable1, null, null);// 设置到控件中
        pageNum = 1;

        requestLeagueData(course_flag);
    }


    @Override
    public void onResume() {
        super.onResume();
        //自动播
        hotChildBanner.startAutoPlay();

    }

    @Override
    protected void initView() {
        setTitle("私教课/操课");
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setEnableLoadMore(false);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            id = bundle.getInt("id", -1);
        }

        // 找到资源图片// 这一步必须要做，否则不会显示。
        drawable = getResources().getDrawable(R.mipmap.icon_class);
        // 找到资源图片// 这一步必须要做，否则不会显示。
        drawable1 = getResources().getDrawable(R.mipmap.icon_class_no);

        //设置广告指示器
        hotChildBanner.setIndicatorGravity(BannerConfig.CENTER);

        personalAdapter = new QuickAdapter<StoreDetailPersonalBean.MapData.DataData>(this, R.layout.item_course_list) {
            @Override
            protected void convert(BaseAdapterHelper helper, StoreDetailPersonalBean.MapData.DataData item) {
                ImageView photo = helper.getView(R.id.photo);
                Glide.with(context)
                        .load(item.getPhoto_urls().contains(",") ? item.getPhoto_urls().substring(0, item.getPhoto_urls().indexOf(",")) : item.getPhoto_urls())
                        .error(R.mipmap.default_big_bg)
                        .into(photo);
//                helper.setText(R.id.title,item.getDic_curriculum_category_name());
                helper.getView(R.id.title).setVisibility(View.GONE);
                helper.getView(R.id.time_address).setVisibility(View.GONE);
            }
        };

        leagueAdapter = new QuickAdapter<StoreDetailLeagueBean.MapData.PageInfoData.ListData>(this, R.layout.item_course_list) {
            @Override
            protected void convert(BaseAdapterHelper helper, StoreDetailLeagueBean.MapData.PageInfoData.ListData item) {
                ImageView photo = helper.getView(R.id.photo);
                Glide.with(context)
                        .load(item.getPhoto_urls().contains(",") ? item.getPhoto_urls().substring(0, item.getPhoto_urls().indexOf(",")) : item.getPhoto_urls())
                        .error(R.mipmap.default_big_bg)
                        .into(photo);
                helper.setText(R.id.title, item.getName());
                helper.setText(R.id.time_address, item.getStart_time().substring(item.getStart_time().indexOf(" ") + 1) + "-" + item.getEnd_time().substring(item.getEnd_time().indexOf(" ") + 1));
            }
        };

        listview.setAdapter(personalAdapter);
        listview.setFocusable(false);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (flag.equals("personal")) {
                    Bundle bundle1 = new Bundle();
                    bundle1.putInt("storeId", StoreDetailActivity.this.id);
                    bundle1.putInt("dicCurriculumCategoryId", personalAdapter.getItem(position).getDic_curriculum_category_id());
                    startActivity(PersonalSelectActivity.class, bundle1);
                } else {
                    Bundle bundle1 = new Bundle();
                    bundle1.putInt("storeId", StoreDetailActivity.this.id);
                    bundle1.putInt("courseId", leagueAdapter.getItem(position).getId());
                    startActivity(CourseDetailActivity.class, bundle1);
                }
            }
        });

        dateRequest();
    }

    @Override
    protected void initData() {
        dateRequest();
        requestPersonalData();
    }

    @Override
    public void onStop() {
        super.onStop();
        //停止
        hotChildBanner.stopAutoPlay();

    }

    /**
     * 判断当前日期是星期几
     *
     * @param pTime 设置的需要判断的时间  //格式如2012-09-08
     * @return dayForWeek 判断结果
     * @Exception 发生异常
     */
    private String getWeek(String pTime) {

        String Week = "周";

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(format.parse(pTime));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
            Week += "日";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
            Week += "一";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY) {
            Week += "二";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY) {
            Week += "三";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY) {
            Week += "四";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
            Week += "五";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
            Week += "六";
        }

        return Week;
    }

    @Override
    @OnClick({R.id.personal_calss, R.id.league_class, R.id.course1, R.id.course2, R.id.course3})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.personal_calss:
                if (!"personal".equals(flag)) {
                    flag = "personal";
                    personalCalss.setTextColor(Color.parseColor("#666666"));
                    personalCalss.setBackgroundColor(Color.parseColor("#ffffff"));
                    leagueClass.setTextColor(Color.parseColor("#ffffff"));
                    leagueClass.setBackgroundColor(Color.parseColor("#d9b878"));
                    classLl.setVisibility(View.GONE);
                    refreshLayout.setEnableLoadMore(false);
                    listview.setAdapter(null);
                    listview.setAdapter(personalAdapter);
                    requestPersonalData();
                }
                break;
            case R.id.league_class:
                if (!"league".equals(flag)) {
                    flag = "league";
                    leagueClass.setTextColor(Color.parseColor("#666666"));
                    leagueClass.setBackgroundColor(Color.parseColor("#ffffff"));
                    personalCalss.setTextColor(Color.parseColor("#ffffff"));
                    personalCalss.setBackgroundColor(Color.parseColor("#d9b878"));
                    classLl.setVisibility(View.VISIBLE);
                    refreshLayout.setEnableLoadMore(true);
                    listview.setAdapter(null);
                    listview.setAdapter(leagueAdapter);
                    courseRefresh();
                }
                break;
            case R.id.course1:
                if (5 != course_flag) {
                    courseRefresh();
                }
                break;
            case R.id.course2:
                if (6 != course_flag) {
                    course_flag = 6;
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());// 设置图片宽高
                    course2.setCompoundDrawables(null, drawable, null, null);// 设置到控件中
                    drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());// 设置图片宽高
                    course1.setCompoundDrawables(null, drawable1, null, null);// 设置到控件中
                    drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());// 设置图片宽高
                    course3.setCompoundDrawables(null, drawable1, null, null);// 设置到控件中
                    pageNum = 1;
                    dateRequest();
                    requestLeagueData(course_flag);
                }
                break;
            case R.id.course3:
                if (7 != course_flag) {
                    course_flag = 7;
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());// 设置图片宽高
                    course3.setCompoundDrawables(null, drawable, null, null);// 设置到控件中
                    drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());// 设置图片宽高
                    course2.setCompoundDrawables(null, drawable1, null, null);// 设置到控件中
                    drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());// 设置图片宽高
                    course1.setCompoundDrawables(null, drawable1, null, null);// 设置到控件中
                    pageNum = 1;
                    dateRequest();
                    requestLeagueData(course_flag);
                }
                break;
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        requestLeagueData(course_flag);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        if (flag.equals("personal")) {
            requestPersonalData();
        } else {
            pageNum = 1;
            requestLeagueData(course_flag);
        }
    }
}
